package com.maddox.relax.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import androidx.fragment.app.FragmentActivity;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.MessageDigestSpi;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 通用的工具类
 */
@SuppressWarnings("all")
public class AppUtils {

    /**
     * dp转px
     */
    public static int dp2px(Context context, int dp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return (int) (dp * metrics.density + 0.5f);
    }

    /**
     * AES加密
     *
     * @param content 加密内容
     * @param pwd     密钥
     * @return
     */
    public static String aesEncrypt(String content, String pwd) {

        byte[] encode = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance("AES");
            SecretKey key = new SecretKeySpec(pwd.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(content.getBytes());
            encode = Base64.getEncoder().encode(doFinal);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(encode);
    }

    /**
     * AES解密
     *
     * @param content 解密内容
     * @param pwd     密钥
     * @return
     */
    public static String aesDecrypt(String content, String pwd) {
        byte[] doFinal = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance("AES");
            SecretKey key = new SecretKeySpec(pwd.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decode = Base64.getDecoder().decode(content);
            doFinal = cipher.doFinal(decode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(doFinal);

    }

    /**
     * 字节数组转16进制
     *
     * @param bytes
     * @return
     */
    public static String byteArrayToHexString(byte[] bytes) {
        int a, b, c;
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            a = bytes[i] & 0xff;
            b = (a >> 4) & 0x0f;
            sb.append(hex[b]);
            b = a & 0x0f;
            sb.append(hex[b]);
        }
        return sb.toString();
    }


    //临时记录变量
    private static long tempSize = 0;

    /**
     * @param file 获取指定目录的总文件大小
     * @return
     */
    public static long fileSize(File file) {
        long totalSize = 0;
        getFileSize(file);
        totalSize = tempSize;
        tempSize = 0;
        return totalSize;
    }

    private static void getFileSize(File file) {
        if (file.isFile()) {
            tempSize += file.length();
        } else if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File item : files) {
                getFileSize(item);
            }
        }
    }

    /**
     * 对指定文本内容进行MD5的生成
     *
     * @param content 生成Md5的内容
     */
    public static String getMD5(String content) {

        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] bytes = digest.digest(content.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte aByte : bytes) {
                int number = aByte & 0xff;
                String hex = Integer.toHexString(number);
                if (hex.length() == 1) {
                    sb.append("0" + hex);
                } else {
                    sb.append(hex);
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();

        }
        return "";
    }
    /**
     * 获取指定文件的MD5
     * @param filePath 文件路径
     * @return MD5生成码
     */
    public static String getMd5Code(String filePath) {
        InputStream is = null;

        try {
            is = new FileInputStream(filePath);
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = is.read(bys)) != -1) {
                digest.update(bys, 0, len);
            }
            byte[] resBytes = digest.digest();
            StringBuffer sb = new StringBuffer();
            for (byte aByte : resBytes) {
                int a = aByte & 0xff;
                String hex = Integer.toHexString(a);
                if (hex.length() == 1) {
                    hex = 0 + hex;
                }
                sb.append(hex);
            }
            String md5Str = sb.toString();
            System.out.println("生成MD5:" + md5Str);
            return md5Str;

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("上传异常:" + e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /**
     * 获取格式化的日期
     *
     * @return
     */
    public static String getFormatDate(String format) {
        if (TextUtils.isEmpty(format))
            format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date());
    }

    /**
     * 日期转换
     *
     * @param time 时间戳
     */
    public static String getStrTime(long time) {

        if (time == 0) {
            return "";
        }
        if (String.valueOf(time).length() <= 10) {
            time = time * 1000L;
        }
        Date date = new Date(time);
        if (isToday(date)) {
            return "今天";
        }
        if (isThisMonth(date)) {

            return "本月";
        }

        if (isThisWeek(date)) {

            return "本周";
        }


        return "";
    }

    //判断是不是本周
    private static boolean isThisWeek(Date date) {
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        int nowWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        calendar.setTime(date);
        int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        return nowWeek == paramWeek;
    }


    //判断日期是不是今天
    private static boolean isToday(Date date) {
        return isThisTime(date, "yyyy-MM-dd");
    }

    //判断日期是不是本月
    private static boolean isThisMonth(Date date) {
        return isThisTime(date, "yyyy-MM");
    }


    private static boolean isThisTime(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String param = format.format(date);
        String now = format.format(new Date());
        return param.equals(now);
    }

    //根据视频时长获取分钟秒数
    public static String getVideoDuration(long duration) {

        if (duration < 1000) {
            return "00:01";
        }
        Date date = new Date(duration);
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        return sdf.format(date);
    }

    /**
     * 生成二维码图片
     *
     * @param content    二维码内容
     * @param width      图片宽度
     * @param height     图片高度
     * @param logoBitmap logo中间图
     * @return
     */
    public static Bitmap createQRCodeBitmap(String content, int width, int height, Bitmap logoBitmap) {
        return createQRCodeBitmap(content, width, height, "UTF-8", Color.BLACK, Color.WHITE, logoBitmap, 0.2f);
    }

    public static Bitmap createQRCodeBitmap(String content, int width, int height, String charset, int colorBG, int colorPadding, Bitmap logoBitmap, float logoPercent) {

        if (TextUtils.isEmpty(content)) {
            return null;
        }
        if (width < 0 || height < 0) {
            return null;
        }
        try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            if (!TextUtils.isEmpty(charset)) {
                hints.put(EncodeHintType.CHARACTER_SET, charset);
            }
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = colorBG;//二维码颜色
                    } else {
                        pixels[y * width + x] = colorPadding;// padding颜色
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

            if (logoBitmap != null) {
                return addLogo(bitmap, logoBitmap, logoPercent);
            }
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 向二维码中间添加logo图片
     */
    private static Bitmap addLogo(Bitmap srcBitmap, Bitmap logoBitmap, float logoPercent) {
        if (srcBitmap == null) {
            return null;
        }
        if (logoBitmap == null) {
            return srcBitmap;
        }
        if (logoPercent < 0F || logoPercent > 1F) {
            logoPercent = 0.2F;
        }

        //获取logo尺寸
        int srcWidth = srcBitmap.getWidth();
        int srcHeight = srcBitmap.getHeight();
        int logoWidth = logoBitmap.getWidth();
        int logoHeight = logoBitmap.getHeight();

        //设置画布
        float scaleWidth = srcWidth * logoPercent / logoWidth;
        float scaleHeight = srcHeight * logoPercent / logoHeight;

        //进行绘制
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(srcBitmap, 0, 0, null);
        canvas.scale(scaleWidth, scaleHeight, srcWidth / 2, srcHeight / 2);
        canvas.drawBitmap(logoBitmap, srcWidth / 2 - logoWidth / 2, srcHeight / 2 - logoHeight / 2, null);

        return bitmap;
    }

    /**
     *  对指定路径的图片进行角度校正
     * @param imageFile 源图片路径
     * @return 返回Bitmap
     */
    public static Bitmap getRoutateBitmap(File imageFile) {
        try {
            ExifInterface exifInterface = new ExifInterface(imageFile);
            int rotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
            if (rotation != -1) {
                int degress = 0;
                switch (rotation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degress = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degress = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degress = 270;
                        break;
                }
                Matrix matrix = new Matrix();
                matrix.postRotate(degress);
                Bitmap sourceBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
                Bitmap targetBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, true);
                return targetBitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}
